import axios from 'axios'
import { message } from 'antd'
import { delToken, getToken } from './storage'
import history from './history'

export const baseURL = 'http://geek.itheima.net/v1_0/'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (error.message === 'Network Error') {
      message.error('网络错误')
    } else if (error?.response?.status === 401) {
      delToken()
      message.error('登录过期')
      // window.location.href = '/login'
      history.push('/login')
    } else {
      message.error(error?.response?.data?.message)
    }
    return Promise.reject(error)
  }
)

export default instance
